<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/29/029
 * Time: 18:08
 */

namespace app\api\service;


use app\lib\exception\OrderException;
use think\facade\Env;
use app\api\model\Order as OrderModel;
use app\api\model\OrderBuy as OrderBuyModel;
use app\api\model\OrderRecharge as OrderRechargeModel;
use app\api\model\OrderAfterSale as OrderAfterSaleModel;
use app\api\model\OrderBuyAfterSale as OrderBuyAfterSaleModel;

include_once Env::get('root_path') . 'extend/Alipay/AopSdk.php';

class Alipay {

    /**
     * 支付宝app端支付信息
     * @param $model
     * @param $id
     * @param int $use_clothes_money
     * @return string
     * @throws OrderException
     */

    public static function getAlipayDate($model, $id, $use_clothes_money) {
        $uid = Token::getCurrentUid();

        switch ($model) {
            case 'order':
                $order = OrderModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_buy' :
                $order = OrderBuyModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_recharge':
                $order = OrderRechargeModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_buy_after_sale':
                $order = OrderBuyAfterSaleModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            case 'order_after_sale':
                $order = OrderAfterSaleModel::get(['id' => $id, 'member_id' => $uid]);
                break;
            default:
                throw new OrderException([
                    'msg' => '订单模型错误',
                    'errorCode' => 60010
                ]);
        }

        if (!$order) {
            throw new OrderException();
        }

        if (in_array($model, ['order_buy_after_sale', 'order_after_sale'])){
            if ($order->status != 2) {
                throw new OrderException([
                    'msg' => '订单不是待支付状态',
                    'errorCode' => 60011
                ]);
            }
        } else {
            if ($order->status != 1) {
                throw new OrderException([
                    'msg' => '订单不是待支付状态',
                    'errorCode' => 60011
                ]);
            }
        }

        // 订单金额
        if (in_array($model, ['order_recharge', 'franchise_order'])) {
            $price = $order['money'];
        } else {
            $price = $order['price'];
        }

        // 如果是用了衣币支付，根据账户衣币计算剩余待支付金额
        if ($use_clothes_money && ($model == 'order' || $model == 'order_after_sale')) {
            $clothes_money = $order->orderMember->clothes_money_recharge + $order->orderMember->clothes_money_donate;
            $price = $clothes_money > $order->price ? 0 : $order->price - $clothes_money;
        }

        // 售后单支付时获取售后单号
        if ($model == 'order_buy_after_sale' || $model == 'order_after_sale') {
            $order_sn = $order['aftermarket_sn'];
        } else {
            $order_sn = $order['order_sn'];
        }

        // 测试阶段  支付金额设为0.01
//                    $price = 0.01;
        //            Loader::import('Alipay.aop.AopClient');

        $alipay_config = config('alipay.');

        $c = new \AopClient;
        $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $c->appId = $alipay_config['appId'];
        // 开发者私钥
        $c->rsaPrivateKey = $alipay_config['rsaPrivateKey'];
        $c->format = "json";
        $c->charset= "utf-8";
        $c->signType= "RSA2";
        // 支付宝公钥
        $c->alipayrsaPublicKey = $alipay_config['alipayrsaPublicKey'];
        //实例化具体API对应的request类,类名称和接口名称对应
        $request = new \AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        //此次只是参数展示，未进行字符串转义，实际情况下请转义
        $bizContent = "{" .
            "    \"subject\":\"衣依不舍订单支付\"," .
            "    \"out_trade_no\":\"$order_sn\"," .
            "    \"total_amount\":\"$price\"," .
            "    \"product_code\":\"QUICK_MSECURITY_PAY\"" .
            " }";

        $request->setBizContent($bizContent);
        $request->setNotifyUrl(request()->domain() . '/api/pay/ali_notify');
        $response= $c->sdkExecute($request);

        return $response;
    }
}